package WWW::VKontakte::API;
use strict;

# a pseudo-API for vkontakte.ru

use LWP::UserAgent;

use base qw(Class::Accessor);

__PACKAGE__->mk_accessors(qw(email password));

sub new {
	my $class = shift;
	my $self = $class->SUPER::new(@_);
	$self->{ua} = LWP::UserAgent->new(
		requests_redirectable => ['GET', 'HEAD', 'POST'],
		timeout => 30,
		cookie_jar => {} )
			or die "cannot create ua";
	return bless $self, $class;
}


sub login {
	my $self = shift;
	my $res = $self->{ua}->post( "http://login.vk.com/?act=login&to=&from_host=pda.vkontakte.ru&pda=1",
		{ email => $self->email, pass => $self->password } );
	#warn "login: ".$res->content;
	$res->is_success or die "cannot login";
	$res->content =~ /<input.+?name='s'.+?value='(\w+)'/ or die "something wrong";
	$res = $self->{ua}->post( "http://pda.vkontakte.ru/login?op=slogin",
		{ s => $1, redirect => 1, expire => 0, op => 'slogin' } );
	#warn "login2: ".$res->content;
	$res->is_success or die "cannot login";
	$res->content =~ /friends/ or die "something wrong";
	$res->content !~ /<div id="error"/ or die "wrong login or password";
	return $self;
}


sub logout {
	my $self = shift;
	my $res = $self->{ua}->get( "http://pda.vkontakte.ru/logout" );
	$res->is_success or die "cannot logout";
	return $self;
}


sub set_activity {
	my $self = shift;
	my ($status) = @_;
	my $res = $self->{ua}->get( "http://pda.vkontakte.ru/setstatus" );
	$res->is_success or die "cannot get status form";
	$res->content =~ /<input type="hidden" name="activityhash" value="(\w+)"/ or die "bad status form: ".$res->content;
	$res = $self->{ua}->post( "http://pda.vkontakte.ru/dosetstatus?pda=1",
		{ activityhash => $1, setactivity => $status } );
	$res->is_success or die "cannot set activity";
	return $self;
}


1;

